import React, { useEffect, useState } from "react";
import { Button, Row, Col, Form, Input, Statistic, message, Space } from 'antd';
import { MessageOutlined, PhoneOutlined } from '@ant-design/icons';
import { _getCode, phoneNumberTest } from '@/service/service';
import {_saleRegister} from "./service";
import { LeftOutlined } from '@ant-design/icons';

const { Countdown } = Statistic;

const UserPhone: React.FC = () => {
    const [codeBtnState, setCodeBtnState] = useState(true),
    [phone, setPhone] = useState<any>(),
    [deadline, setDeadline] = useState<number>();
    const sale_token = window.location.search.substring(1).split('tuiguang_code=')[1];
    useEffect(() => {
        const fetchData = async () => {
        }
        fetchData()
    }, [])


    const getCode = async () => {
        !!phoneNumberTest(phone) && await _getCode({
            phone: phone,
            template_id: 'C4'
        }).then((res) => {
            // setPhone(_phone)
            if (res.status === 200) {
                setCodeBtnState(t => !t);
                setDeadline(Date.now() + 60 * 1000);
                res.data.code === 200 && message.success('验证码已发送！', 1.5);
            }
        })
    }

    const onFinish = async (values) => {
        !!values && await _saleRegister({
            phone: phone,
            code: values.code,
            sale_token: sale_token
        }).then((dataRes)=>{
            if(dataRes.data.code === 200){
                alert('前往小程序！')   
                window.location.href="weixin://dl/business/?t=CwLRZoOgr1u";
            }else{
                message.error(dataRes.data.msg)
            }
        })
    }

    return (
        <div className="login">
            <div className="header">
        <a className="goback" onClick={() => { window.history.back() }} ><LeftOutlined /></a>
        <div className="header-title">
        绑定手机号
        </div>
      </div>
            <div className="login-main">
                    <Form name="login" className="login-form" onFinish={onFinish}  >
                        <h1>绑定手机号</h1>
                        <Form.Item
                            className="form-item"
                            name="phone"
                            validateFirst="parallel"
                            validateTrigger="onBlur"
                            rules={[
                                { required: true, message: '请输入手机号码！' },
                                () => ({
                                    validator(_, value) {
                                        if ((/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/).test(value)) {
                                            setPhone(value)
                                            return Promise.resolve();
                                        }
                                        return Promise.reject(new Error('请输入正确的手机号！'));
                                    },
                                }),
                            ]}
                        >
                            <Input
                                prefix={<PhoneOutlined rotate={180} style={{ fontSize: '18px', color: '#d4d4d4' }}
                                className="site-form-item-icon" />}
                                placeholder="手机号码"
                            />
                        </Form.Item>
                        <Form.Item className="form-item">
                            <Row gutter={8}>
                                <Col span={14}>
                                    <Form.Item
                                        name="code"
                                        noStyle
                                        rules={[{ required: true, message: '请输入验证码!' }]}>
                                        <Input
                                            prefix={<MessageOutlined style={{ fontSize: '18px', color: '#d4d4d4' }}
                                            className="site-form-item-icon" />}
                                            autoComplete="off"
                                            placeholder="短信验证码"
                                        />
                                    </Form.Item>
                                </Col>
                                <Col span={10}>
                                    <Button className="getcode" type="primary" size="small" onClick={getCode} disabled={!codeBtnState} >
                                        {
                                            !codeBtnState ?
                                                <Space size="small">
                                                    <span>已发送</span>
                                                    <Countdown onFinish={() => setCodeBtnState(t => !t)} style={{ visibility: codeBtnState ? 'hidden' : 'visible', lineHeight: '0', }} valueStyle={{ fontSize: '15px', color: '#d0d0d0', letterSpacing: '0' }} value={deadline} format="s" />
                                                </Space> : '获取验证码'
                                        }
                                    </Button>
                                </Col>
                            </Row>
                        </Form.Item>
                        <Form.Item className="form-item">
                            <Button shape="round" type="primary" size="large" block htmlType="submit">绑定手机号</Button>
                        </Form.Item>
                    </Form>
                    
            </div>
        </div>
    )
}

export default UserPhone;
